//
//  LoginViewController.m
//  shuiyun
//
//  Created by 马田成 on 2017/9/5.
//  Copyright © 2017年 qianyi. All rights reserved.
//

#import "LoginViewController.h"
#import "MyTabBarController.h"
#import "SettingPasswardMViewController.h"
@interface LoginViewController ()<UITextFieldDelegate>
{

    NSString *type;
    NSString *phoneID;
}

@property (nonatomic, strong) MyTabBarController *tabBarController;
@property (nonatomic, strong) UIButton *buttonOfLogin;//登录
@property (nonatomic, strong) UIButton *buttonOfRegister;//注册
@property (nonatomic, strong) UIView *viewOfBlue;
@property (nonatomic, strong) UIView *registerView;
@property (nonatomic, strong) UITextField *phoneTF;//手机号
@property (nonatomic, strong) UITextField *phonePassward;//密码
@property (nonatomic, strong) UIButton *buttonForPassward;//忘记密码
@property (nonatomic, strong) UIView *loginView;//登录rootview
@property (nonatomic, strong) UIView *zcView;//注册rootview
@property (nonatomic, strong) UIButton *buttonOfEye;//可见
//注册
@property (nonatomic, strong) UITextField *zcPhoneTF;//注册手机
@property (nonatomic, strong) UITextField *zcYZMTF;//注册验证码
@property (nonatomic, strong) UIButton *buttonYZM;//验证码


@end

@implementation LoginViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self creationView];
    // Do any additional setup after loading the view from its nib.
}
- (void)creationView{

    UILabel *labelOfTitle = [[UILabel alloc] init];
    [self.view addSubview:labelOfTitle];
    labelOfTitle.text = @"华东水运";
    [labelOfTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(53);
        make.centerX.equalTo(self.view);
        make.height.offset(19);
        
    }];
    labelOfTitle.font = [UIFont systemFontOfSize:19];
    labelOfTitle.textColor = getColor(@"262626");
  //登录
    self.loginView = [[UIView alloc] initWithFrame:CGRectMake(0, 200, DEF_SCREEN_WIDTH, 180)];
    [self.view addSubview:self.loginView];
    self.loginView.backgroundColor = [UIColor whiteColor];
    
    self.buttonOfLogin = [[UIButton alloc] init];
    [self.view addSubview:self.buttonOfLogin];
    [self.buttonOfLogin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(labelOfTitle.mas_bottom).with.offset(70);
        make.left.equalTo(self.view).with.offset(100);
        make.height.offset(25);
        
    }];
    [self.buttonOfLogin setTitle:@"登录" forState:UIControlStateNormal];
    
    [self.buttonOfLogin setTitleColor:getColor(@"3F87F6") forState:UIControlStateNormal];

    [self.buttonOfLogin addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.buttonOfRegister = [[UIButton alloc] init];
    [self.view addSubview:self.buttonOfRegister];
    [self.buttonOfRegister mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(labelOfTitle.mas_bottom).with.offset(70);
        make.right.equalTo(self.view).with.offset(-100);
        make.height.offset(25);
        
    }];
    [self.buttonOfRegister setTitle:@"注册" forState:UIControlStateNormal];
    [self.buttonOfRegister setTitleColor:getColor(@"262626") forState:UIControlStateNormal];
    [self.buttonOfRegister addTarget:self action:@selector(registerBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.viewOfBlue = [[UIView alloc] init];
    [self.view addSubview:self.viewOfBlue];
    [self.viewOfBlue mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.buttonOfLogin.mas_bottom).with.offset(6);
        make.centerX.equalTo(self.buttonOfLogin);
        make.width.offset(50);
        make.height.offset(2);
        
    }];
    self.viewOfBlue.backgroundColor = getColor(@"3F87F6");
    
    self.registerView = [[UIView alloc] init];
    self.registerView.hidden = YES;
    
    [self.view addSubview:self.registerView];
    [self.registerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.buttonOfLogin.mas_bottom).with.offset(6);
        make.centerX.equalTo(self.buttonOfRegister);
        make.width.offset(50);
        make.height.offset(2);
        
    }];
    self.registerView.backgroundColor = getColor(@"3F87F6");
    
    UIView *view111 = [[UIView alloc] init];
    [self.loginView addSubview:view111];
    [view111 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.buttonOfLogin.mas_bottom).with.offset(44);
        make.left.equalTo(self.view).with.offset(65);
        make.right.equalTo(self.view).with.offset(-65);
        make.height.offset(46);
        
    }];
    view111.layer.borderWidth = 1.0f;
    view111.layer.borderColor = getColor(@"eeeeee").CGColor;
    view111.layer.cornerRadius = 23;
    view111.layer.masksToBounds = YES;
    
    //手机号
    self.phoneTF = [[UITextField alloc] init];
    [view111 addSubview:self.phoneTF];
    self.phoneTF.placeholder = @"请输入手机号/姓名";
    [self.phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(view111);
        make.left.equalTo(self.view).with.offset(80);
        make.right.equalTo(self.view).with.offset(-80);
        make.height.offset(40);
    }];
    
    UIView *view1111 = [[UIView alloc] init];
    [self.loginView addSubview:view1111];
    [view1111 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneTF.mas_bottom).with.offset(44);
        make.left.equalTo(self.view).with.offset(65);
        make.right.equalTo(self.view).with.offset(-65);
        make.height.offset(40);
        
    }];
    view1111.layer.borderWidth = 1.0f;
    view1111.layer.borderColor = getColor(@"eeeeee").CGColor;
    view1111.layer.cornerRadius = 23;
    view1111.layer.masksToBounds = YES;
    
    
    self.phonePassward = [[UITextField alloc] init];
    [view1111 addSubview:self.phonePassward];
//    self.phonePassward.secureTextEntry=YES;//密文
    self.phonePassward.placeholder = @"请输入密码";
    [self.phonePassward mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(view1111);
        make.left.equalTo(self.view).with.offset(80);
        make.right.equalTo(view1111).with.offset(-30);
        make.height.offset(40);
    }];
    //是不是可见
    self.buttonOfEye = [[UIButton alloc] init];
    [view1111 addSubview:self.buttonOfEye];
    [self.buttonOfEye setImage:[UIImage imageNamed:@"login_icon_kejian"] forState:UIControlStateNormal];
    
    [self.buttonOfEye setImage:[UIImage imageNamed:@"login_icon_bukejian"] forState:UIControlStateSelected];
    
    
    [self.buttonOfEye mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(view1111);
        make.right.equalTo(view1111).with.offset(-19);
        
    }];
    [self.buttonOfEye addTarget:self action:@selector(eyeClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    self.buttonForPassward = [[UIButton alloc] init];
    [self.buttonForPassward setTitle:@"忘记密码" forState:UIControlStateNormal];
    self.buttonForPassward.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.loginView addSubview:self.buttonForPassward];
    [self.buttonForPassward mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phonePassward.mas_bottom).with.offset(9);
        make.right.equalTo(self.view).with.offset(-80);
        make.height.offset(13);
    }];
    [self.buttonForPassward setTitleColor:getColor(@"9A9A9A") forState:UIControlStateNormal];
    
    type = @"1";
    
    
    
    //注册
    
    self.zcView = [[UIView alloc] initWithFrame:CGRectMake(0, 200, DEF_SCREEN_WIDTH, 180)];
    [self.view addSubview:self.zcView];
    self.zcView.backgroundColor = [UIColor whiteColor];
    
    UIView *viewOfZCPhone = [[UIView alloc] init];
    [self.zcView addSubview:viewOfZCPhone];
    [viewOfZCPhone mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.buttonOfLogin.mas_bottom).with.offset(44);
        make.left.equalTo(self.view).with.offset(65);
        make.right.equalTo(self.view).with.offset(-65);
        make.height.offset(46);
        
    }];
    viewOfZCPhone.layer.borderWidth = 1.0f;
    viewOfZCPhone.layer.borderColor = getColor(@"eeeeee").CGColor;
    viewOfZCPhone.layer.cornerRadius = 23;
    viewOfZCPhone.layer.masksToBounds = YES;
    
    self.zcPhoneTF = [[UITextField alloc] init];
    [viewOfZCPhone addSubview:self.zcPhoneTF];
    self.zcPhoneTF.placeholder = @"请输入手机号";
    [self.zcPhoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(viewOfZCPhone);
        make.left.equalTo(self.view).with.offset(80);
        make.right.equalTo(viewOfZCPhone).with.offset(-100);
        make.height.offset(40);
    }];
    
    self.buttonYZM = [[UIButton alloc] init];
    [viewOfZCPhone addSubview:self.buttonYZM];
    [self.buttonYZM mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(viewOfZCPhone);
        make.left.equalTo(self.zcPhoneTF.mas_right).with.offset(10);
        make.height.offset(15);
        
    }];
    [self.buttonYZM setTitle:@"获取验证码" forState:UIControlStateNormal];
    self.buttonYZM.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.buttonYZM setTitleColor:getColor(@"565656") forState:UIControlStateNormal];
    [self.buttonYZM addTarget:self action:@selector(yzmClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIView *viewOfZCYZM = [[UIView alloc] init];
    [self.zcView addSubview:viewOfZCYZM];
    [viewOfZCYZM mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(viewOfZCPhone.mas_bottom).with.offset(44);
        make.left.equalTo(self.view).with.offset(65);
        make.right.equalTo(self.view).with.offset(-65);
        make.height.offset(46);
        
    }];
    viewOfZCYZM.layer.borderWidth = 1.0f;
    viewOfZCYZM.layer.borderColor = getColor(@"eeeeee").CGColor;
    viewOfZCYZM.layer.cornerRadius = 23;
    viewOfZCYZM.layer.masksToBounds = YES;
    
    self.zcYZMTF = [[UITextField alloc] init];
    [viewOfZCYZM addSubview:self.zcYZMTF];
    self.zcYZMTF.placeholder = @"请输入验证码";
    [self.zcYZMTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(viewOfZCYZM);
        make.left.equalTo(self.view).with.offset(80);
        make.right.equalTo(viewOfZCYZM).with.offset(-10);
        make.height.offset(40);
    }];
    
    
    

    self.loginView.hidden = NO;
    self.zcView.hidden = YES;
    
    

    self.zcPhoneTF.keyboardType = UIKeyboardTypeNumberPad;
    self.zcPhoneTF.delegate = self;
    self.zcYZMTF.keyboardType =UIKeyboardTypeNumberPad;
    self.zcYZMTF.delegate = self;
    self.phonePassward.delegate = self;
    self.phonePassward.keyboardType =UIKeyboardTypeNumberPad;
    self.phoneTF.delegate = self;

    
}

//登录
- (void)loginBtnClick{
    
    type = @"1";

    self.registerView.hidden = YES;
    self.viewOfBlue.hidden = NO;
    
    [self.buttonOfLogin setTitleColor:getColor(@"3F87F6") forState:UIControlStateNormal];
    
    [self.buttonOfRegister setTitleColor:getColor(@"262626") forState:UIControlStateNormal];
    self.loginView.hidden = NO;
    self.zcView.hidden = YES;
    
}
//注册
- (void)registerBtnClick{

    type = @"3";
    self.viewOfBlue.hidden = YES;
    self.registerView.hidden = NO;
    [self.buttonOfRegister setTitleColor:getColor(@"3F87F6") forState:UIControlStateNormal];
    [self.buttonOfLogin setTitleColor:getColor(@"262626") forState:UIControlStateNormal];
    self.loginView.hidden = YES;
    self.zcView.hidden = NO;
    
}
//是不是可见
- (void)eyeClick:(UIButton *)sender{

    sender.selected = !sender.selected;
    if (sender.selected) {
        
        self.phonePassward.secureTextEntry=YES;
    }else {
    
        self.phonePassward.secureTextEntry=NO;
    }
    

    
}
- (IBAction)login:(UIButton *)sender {
    
    if ([type isEqualToString:@"1"]) {
        
        //登录
        NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];

        
        [productParams setValue:self.phoneTF.text forKey:@"username"];
        [productParams setValue:self.phonePassward.text forKey:@"pass"];
        
//        [productParams setValue:@"admin" forKey:@"username"];
//        [productParams setValue:@"123456" forKey:@"pass"];
        
        
        [[MNetworkHandler sharedInstance]conURL:hometLogicChecklogin networkType:NetWorkPOST params:productParams delegate:nil showHUD:NO successBlock:^(id returnData) {
            

            if ([[returnData objectForKey:@"code"]intValue]==1) {
                
                NSMutableDictionary *dic = [returnData objectForKey:@"data"];
                
                
                [PublicFunction saveConfig:[dic objectForKey:@"token"] forKey:@"token"];
                [PublicFunction saveConfig:[dic objectForKey:@"userid"] forKey:@"userid"];

                UINavigationBar *bar = [UINavigationBar appearance];
                
                
                bar.barStyle=UIBarStyleBlackTranslucent;
                
                //设置显示的颜色
                
                bar.barTintColor =[ZJCModel colorWithString:@"3F87F6"];
                
                //设置字体颜色
                
                bar.tintColor = [UIColor whiteColor];
                
                
                [bar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
                MyTabBarController *barController = [[MyTabBarController alloc] init];
                // TAB BAR
                
                [self presentViewController:barController animated:YES completion:nil];

                
                
            }
            
            
            else {
                
                
                [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                
                
            }
            
            
        } failureBlock:^(NSError *error) {
            
            NSLog(@"%@",error);
            
            [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
            
            
        }];

        
        
        
           }else if ([type isEqualToString:@"2"]) {
    
        
        
        NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
        
        [productParams setValue:phoneID forKey:@"id"];
        [productParams setValue:self.zcYZMTF.text forKey:@"code"];
        [productParams setValue:self.zcPhoneTF.text forKey:@"phone"];
        
        [[MNetworkHandler sharedInstance]conURL:hometRegisterCheckcode networkType:NetWorkPOST params:productParams delegate:nil showHUD:NO successBlock:^(id returnData) {
        
        
            
            if ([[returnData objectForKey:@"code"]intValue]==1) {
        

                SettingPasswardMViewController *vc = [[SettingPasswardMViewController alloc] init];
                vc.phoneID = phoneID;
                vc.code = self.zcYZMTF.text;
                vc.phone = self.zcPhoneTF.text;
                

                [self presentViewController:vc animated:YES completion:nil];

                
            }
        
            
            else {
        
                
                [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
        
                
            }
        
            
        } failureBlock:^(NSError *error) {
                
                NSLog(@"%@",error);
                
                [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                
            
        }];

        
        
        
       
        
    }else {
    
        
        
    }
    
    
}
- (void)yzmClick{

    NSMutableDictionary *loginParams=[[NSMutableDictionary alloc]init];
    [loginParams setValue:self.zcPhoneTF.text forKey:@"phone"];
    
    [[MNetworkHandler sharedInstance]conURL:hometRegisterSmssend
                                networkType:NetWorkPOST
                                     params:loginParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   
                                   if ([returnData[@"code"] intValue] == 1) {
                                       
                                       NSMutableDictionary *dic = [returnData objectForKey:@"data"];
                                       phoneID = [dic objectForKey:@"id"];
                                       NSLog(@"%@", phoneID);
                                       
                                       
                                       [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                       
                                       type = @"2";
                                       __block int timeout=60; //倒计时时间
                                       dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                                       dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                                       dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
                                       
                                       dispatch_source_set_event_handler(_timer, ^{
                                           
                                           if(timeout<=0){ //倒计时结束，关闭
                                               
                                               dispatch_source_cancel(_timer);
                                               dispatch_async(dispatch_get_main_queue(), ^{
                                                   //设置界面的按钮显示 根据自己需求设置
                                                   [self.buttonYZM setTitle:@"发送验证码" forState:UIControlStateNormal];
                                                   
                                                   self.buttonYZM.userInteractionEnabled = YES;
                                               });
                                           }else{
                                               int seconds = timeout % 61;
                                               
                                               NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                                               dispatch_async(dispatch_get_main_queue(), ^{
                                                   //设置界面的按钮显示 根据自己需求设置
                                                   //NSLog(@"____%@",strTime);
                                                   [UIView beginAnimations:nil context:nil];
                                                   [UIView setAnimationDuration:1];
                                                   [self.buttonYZM setTitle:[NSString stringWithFormat:@"%@秒",strTime] forState:UIControlStateNormal];
                                                   [UIView commitAnimations];
                                                   self.buttonYZM.userInteractionEnabled = NO;
                                               });
                                               timeout--;
                                           }
                                       });
                                       dispatch_resume(_timer);
                                   }else{
                                       
                                       [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                   }
                                   
                               }
                               failureBlock:^(NSError *error) {
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                               }];

    
    
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    
    if (textField == _zcPhoneTF) {
        
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        
        if (existedLength - selectedLength + replaceLength > 11) {
            return NO;
        }
    }
    if (textField == _phoneTF) {
        
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        
        if (existedLength - selectedLength + replaceLength > 11) {
            return NO;
        }
    }
    
    if (textField == _zcYZMTF) {
        
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        
        if (existedLength - selectedLength + replaceLength > 4) {
            return NO;
        }
    }
    
    
    NSCharacterSet *cs;
    
    if (textField == _phonePassward ) {
        
        cs = [[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        BOOL basicTest = [string isEqualToString:filtered];
        if(!basicTest)  {
            return NO;
        }
        
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        
        if (existedLength - selectedLength + replaceLength > 16) {
            return NO;
        }
    }


    
    return YES;
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
